/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.KwExamPlan;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.mapper.*;
import me.zhengjie.pojo.dto.ExamPlanFindPageDto;
import me.zhengjie.pojo.entity.ExamPlan;
import me.zhengjie.pojo.entity.User;
import me.zhengjie.repository.KwExamPlanRepository;
import me.zhengjie.repository.KwExamRepository;
import me.zhengjie.service.KwExamPlanService;
import me.zhengjie.service.dto.KwExamPlanDto;
import me.zhengjie.service.dto.KwExamPlanQueryCriteria;
import me.zhengjie.service.mapstruct.KwExamPlanMapper;
import me.zhengjie.util.KwUtils;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-06-28
 **/
@Service
@RequiredArgsConstructor
public class KwExamPlanServiceImpl implements KwExamPlanService {

    private final KwExamRepository kwExamRepository;
    private final KwExamPlanRepository kwExamPlanRepository;
    private final KwExamPlanMapper kwExamPlanMapper;

    private final SysUsersRolesMapper sysUsersRolesMapper;
    private final ExamPlanMapper examPlanMapper;


    private final DeptMapper deptMapper;
    private final UserMapper userMapper;
    private final ExamTeacherMapper examTeacherMapper;
    private final KwUtils kwUtils;


    @Override
    public Map<String, Object> queryAll(ExamPlanFindPageDto dto, Pageable pageable) {
        Set<Long> roles = kwUtils.getRoles();
        User user = kwUtils.getUser();
        Set<Integer> examIds = kwUtils.getExamIds();
        Long userId = SecurityUtils.getCurrentUserId();
        //如果当前登录用户没有任何角色直接返回
        if (roles == null || roles.isEmpty()) return null;
        //是否考试管理员
        boolean isExam = false;
        //是否部门管理员
        boolean isDept = false;
        //是否系统管理员
        boolean isAdmin = false;
        //是否当前查询考试的部门管理员
        boolean isExamDept = true;
        for (Integer examId : examIds) {
            if (Objects.equals(examId, dto.getExamId())) {
                isExamDept = false;
            }
        }

        for (Long roleId : roles) {
            if (Objects.equals(roleId, 5L)) {
                isExam = true;
            }
            if (Objects.equals(roleId, 6L)) {
                isDept = true;
            }
            if (Objects.equals(roleId, 1L)) {
                isAdmin = true;
            }
        }
        /*获取当前登录用户拥有的所有总考试*/
        List<ExamPlan> list = examPlanMapper.findPageIsExam(dto, user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Integer count = examPlanMapper.findCount(dto, user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", list);
        map.put("totalElements", count == null ? 0 : count);
        return map;
    }

    @Override
    public List<KwExamPlanDto> queryAll(KwExamPlanQueryCriteria criteria) {
        return kwExamPlanMapper.toDto(kwExamPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public KwExamPlanDto findById(Integer id) {
        KwExamPlan kwExamPlan = kwExamPlanRepository.findById(id).orElseGet(KwExamPlan::new);
        ValidationUtil.isNull(kwExamPlan.getId(), "KwExamPlan", "id", id);
        return kwExamPlanMapper.toDto(kwExamPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KwExamPlanDto create(KwExamPlan resources) {
        return kwExamPlanMapper.toDto(kwExamPlanRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KwExamPlan resources) {
        KwExamPlan kwExamPlan = kwExamPlanRepository.findById(resources.getId()).orElseGet(KwExamPlan::new);
        ValidationUtil.isNull(kwExamPlan.getId(), "KwExamPlan", "id", resources.getId());
        kwExamPlan.copy(resources);
        kwExamPlanRepository.save(kwExamPlan);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        List<KwExamPlan> kwExamPlans = kwExamPlanRepository.findAllById(Arrays.asList(ids));
        List<Integer> examIds = kwExamPlans.stream().map(KwExamPlan::getExamId).collect(Collectors.toList());
        boolean permission = kwUtils.isPermission(examIds);
        if (!permission) throw new ParameterException("无权操作");
        for (Integer id : ids) {
            kwExamPlanRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<KwExamPlanDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (KwExamPlanDto kwExamPlan : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("考试id", kwExamPlan.getExamId());
            map.put("部门id", kwExamPlan.getDeptId());
            map.put("监考老师上报数量", kwExamPlan.getTeacherNumber());
            map.put("考务人员上报数量", kwExamPlan.getStaffNumber());
            map.put("备注信息", kwExamPlan.getRemark());
            map.put("删除标志（0.未删除，1.已删除）", kwExamPlan.getDelFlag());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 分页查询考试任务
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public Map<String, Object> findPage(ExamPlanFindPageDto dto) {
        Set<Long> roles = kwUtils.getRoles();
        User user = kwUtils.getUser();
        Set<Integer> examIds = kwUtils.getExamIds();
        Long userId = SecurityUtils.getCurrentUserId();
        //如果当前登录用户没有任何角色直接返回
        if (roles == null || roles.isEmpty()) return null;
        //是否考试管理员
        boolean isExam = false;
        //是否部门管理员
        boolean isDept = false;
        //是否系统管理员
        boolean isAdmin = false;
        //是否当前查询考试的部门管理员
        boolean isExamDept = true;
        for (Integer examId : examIds) {
            if (Objects.equals(examId, dto.getExamId())) {
                isExamDept = false;
            }
        }

        for (Long roleId : roles) {
            if (Objects.equals(roleId, 5L)) {
                isExam = true;
            }
            if (Objects.equals(roleId, 6L)) {
                isDept = true;
            }
            if (Objects.equals(roleId, 1L)) {
                isAdmin = true;
            }
        }
        /*获取当前登录用户拥有的所有总考试*/
        List<ExamPlan> list = examPlanMapper.findPageIsExam(dto, user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Integer count = examPlanMapper.findCount(dto, user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", list);
        map.put("totalElements", count == null ? 0 : count);
        return map;
    }

}